#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
import time

def test_generate_plan():
    """测试生成应急预案"""
    print("🔄 测试生成应急预案...")
    
    data = {
        "event_type": "网络安全事件",
        "event_subtype": "数据勒索事件",
        "optimize_field": "",
        "optimize_suggest": "",
        "history": []
    }
    
    try:
        response = requests.post(
            'http://localhost:8080/api/v1/generate_plan',
            json=data,
            headers={'Content-Type': 'application/json'},
            timeout=30
        )
        
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print("✅ 生成预案成功！")
            print(f"状态码: {result.get('status_code')}")
            print(f"消息: {result.get('message')}")
            
            plan = result.get('plan', [])
            print(f"预案字段数: {len(plan)}")
            
            # 显示预案内容
            for i, field in enumerate(plan, 1):
                print(f"\n{i}. {field.get('field_name', '')}")
                content = field.get('content', '')
                if len(content) > 100:
                    content = content[:100] + "..."
                print(f"   内容: {content}")
            
            return plan
        else:
            print(f"❌ 生成预案失败: {response.text}")
            return None
            
    except Exception as e:
        print(f"❌ 请求异常: {e}")
        return None

def test_save_plan(plan):
    """测试保存应急预案"""
    if not plan:
        print("❌ 没有预案可保存")
        return False
    
    print("\n🔄 测试保存应急预案...")
    
    data = {
        "event_type": "网络安全事件",
        "event_subtype": "数据勒索事件",
        "plan": plan
    }
    
    try:
        response = requests.post(
            'http://localhost:8080/api/v1/save_plan',
            json=data,
            headers={'Content-Type': 'application/json'},
            timeout=30
        )
        
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print("✅ 保存预案成功！")
            print(f"状态码: {result.get('status_code')}")
            print(f"消息: {result.get('message')}")
            
            data = result.get('data', {})
            print(f"文件ID: {data.get('file_id')}")
            print(f"文件名: {data.get('file_name')}")
            
            return True
        else:
            print(f"❌ 保存预案失败: {response.text}")
            return False
            
    except Exception as e:
        print(f"❌ 请求异常: {e}")
        return False

def test_optimize_plan():
    """测试优化应急预案"""
    print("\n🔄 测试优化应急预案...")
    
    # 先生成一个预案
    plan = test_generate_plan()
    if not plan:
        return False
    
    # 优化第一个字段
    optimize_data = {
        "event_type": "网络安全事件",
        "event_subtype": "数据勒索事件",
        "optimize_field": "安全事件监测",
        "optimize_suggest": "增加更详细的监测指标和阈值设置",
        "history": plan
    }
    
    try:
        response = requests.post(
            'http://localhost:8080/api/v1/generate_plan',
            json=optimize_data,
            headers={'Content-Type': 'application/json'},
            timeout=30
        )
        
        print(f"状态码: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print("✅ 优化预案成功！")
            print(f"状态码: {result.get('status_code')}")
            print(f"消息: {result.get('message')}")
            
            optimized_plan = result.get('plan', [])
            print(f"优化后预案字段数: {len(optimized_plan)}")
            
            # 显示优化后的内容
            for field in optimized_plan:
                if field.get('field_name') == '安全事件监测':
                    content = field.get('content', '')
                    if len(content) > 200:
                        content = content[:200] + "..."
                    print(f"优化后的监测内容: {content}")
                    break
            
            return optimized_plan
        else:
            print(f"❌ 优化预案失败: {response.text}")
            return None
            
    except Exception as e:
        print(f"❌ 请求异常: {e}")
        return None

def main():
    print("🚀 开始完整的应急预案API测试...")
    print("=" * 50)
    
    # 1. 测试生成预案
    plan = test_generate_plan()
    
    if plan:
        # 2. 测试保存预案
        save_success = test_save_plan(plan)
        
        if save_success:
            # 3. 测试优化预案
            optimized_plan = test_optimize_plan()
            
            if optimized_plan:
                # 4. 保存优化后的预案
                print("\n🔄 保存优化后的预案...")
                save_optimized = test_save_plan(optimized_plan)
                
                if save_optimized:
                    print("\n🎉 所有测试通过！应急预案生成、优化和保存功能都正常工作！")
                else:
                    print("\n❌ 保存优化预案失败")
            else:
                print("\n❌ 优化预案失败")
        else:
            print("\n❌ 保存预案失败")
    else:
        print("\n❌ 生成预案失败")
    
    print("\n" + "=" * 50)
    print("测试完成！")

if __name__ == "__main__":
    main() 